import type { UserInfo, ExamUserInfo } from '/#/store'
import type { ErrorMessageMode } from '/#/axios'
import { defineStore } from 'pinia'
import { store } from '/@/store'
import { RoleEnum } from '/@/enums/roleEnum'
import { PageEnum } from '/@/enums/pageEnum'
import { ROLES_KEY, TOKEN_KEY, USER_INFO_KEY, EXAM_USER_INFO_KEY } from '/@/enums/cacheEnum'
import { getAuthCache, setAuthCache } from '/@/utils/auth'
import { GetUserInfoModel, LoginParams } from '/@/api/sys/model/userModel'
import { doLogout, loginApi, getsysYear } from '/@/api/sys/user'
import { getConfigInfo } from '/@/api/system-manage/teacher-info'
import { useI18n } from '/@/hooks/web/useI18n'
import { useMessage } from '/@/hooks/web/useMessage'
import { router } from '/@/router'
import { usePermissionStore } from '/@/store/modules/permission'
import { RouteRecordRaw } from 'vue-router'
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic'
import { isArray } from '/@/utils/is'
import { h } from 'vue'
import Watermark from '/@/utils/watermark/watermark' //水印

interface authority {
  createAccount?: string
  createName?: string
  createTime?: string
  createType: string
  remark?: string
  roleCode: string
  roleId: string
  roleName: string
  roleState: "NORMAL" | "DISABLE"
  updateAccount?: string
  updateName?: string
  updateTime?: string
}


interface UserState {
  userInfo: Nullable<UserInfo>
  examUserInfo: Nullable<UserInfo>
  token?: string
  roleList: RoleEnum[]
  sessionTimeout?: boolean
  lastUpdateTime: number
  authorityList: null | any[]
  authorityItem: Nullable<authority>
  // 开始评阅时间
  startTime: string,
  userBehavior: null | any,
  userMySse: null | any,
  sysConfig: any,
}




export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // roleList
    roleList: [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
    examUserInfo: null,
    authorityList: null,
    authorityItem: null,
    startTime: '',
    userBehavior: null,
    userMySse: "",
    sysConfig: {},
  }),
  getters: {
    getSysConfig(): any {
      return this.sysConfig || {}
    },
    getUserInfo(): UserInfo {
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {}
    },
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY)
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0 ? this.roleList : getAuthCache<RoleEnum[]>(ROLES_KEY)
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime
    },
    getInfo(): UserInfo {
      return this.examUserInfo || getAuthCache<ExamUserInfo>(EXAM_USER_INFO_KEY) || {}
    },
    getUserType() {
      return localStorage.setIgetItemtem('USER_TYPE') || ''
    },
    getAuthority(): any[] {
      return this.authorityList || getAuthCache('authoritList') || []
    },
    getAuthorityItem(): authority {
      return this.authorityItem || getAuthCache('authoritItem') || {}
    },
    getStartTime(): string {
      return this.startTime
    },
    getUserMySse(): any {
      return this.userMySse
    },
  },
  actions: {
    async setSysConfig() {
      const { code, data } = await getConfigInfo({})
      if (code === 200) {
        this.sysConfig = data || {}
      } else this.sysConfig = {}
    },
    setToken(info: string | undefined) {
      this.token = info ? info : '' // for null or undefined value
      setAuthCache(TOKEN_KEY, info)
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList
      setAuthCache(ROLES_KEY, roleList)
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info
      this.lastUpdateTime = new Date().getTime()
      setAuthCache(USER_INFO_KEY, info)
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag
    },
    resetState() {
      this.userInfo = null
      this.token = ''
      this.roleList = []
      this.sessionTimeout = false
      this.authorityList = []
      this.authorityItem = null
    },
    setInfo(value) {
      this.examUserInfo = value
    },
    setAuthority(value) {
      this.authorityList = value
      setAuthCache('authoritList', value)
    },
    setAuthorityItem(value) {
      this.authorityItem = value
      setAuthCache('authoritItem', value)
    },
    setStartTime(value) {
      this.startTime = value
    },

    setuserBehavior(value) {
      this.userBehavior = value
    },
    // setUserType(value) {
    //   localStorage.setItem('USER_TYPE', value);
    // },
    setUserMySse(value): any {
      this.userMySse = value
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean
        mode?: ErrorMessageMode
      }
    ) {
      const { goHome = true, mode, ...loginParams } = params
      const { data: kmYear } = await getsysYear({});//获取系统默认年份
      return new Promise<void>((resolve, reject) => {
        loginApi(loginParams)
          .then(async res => {
            if (res.code == 200) {
              const { saToken } = res.data
              const resoObj = { ...res.data, kmYear }
              this.setInfo(resoObj)
              this.setUserInfo(resoObj)
              setAuthCache(EXAM_USER_INFO_KEY, resoObj)
              this.setToken(saToken)
            }
            resolve(res)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
      if (!this.getToken) return null
      // get user info

      const userInfo = await this.getUserInfoAction()

      const sessionTimeout = this.sessionTimeout
      if (sessionTimeout) {
        this.setSessionTimeout(false)
      } else {
        const permissionStore = usePermissionStore()
        let replacRouteStr: string = PageEnum.BASE_HOME
        if (!permissionStore.isDynamicAddedRoute) {
          // 动态添加路由
          const routes = await permissionStore.buildRoutesAction()
          routes.forEach(route => {
            router.addRoute(route as unknown as RouteRecordRaw)
          })
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw)
          permissionStore.setDynamicAddedRoute(true)
          replacRouteStr = this.setBASE_HOME(routes[1])
          if (replacRouteStr == '/home') replacRouteStr = PageEnum.BASE_HOME
        }
        // userInfo?.homePath ||
        goHome && (await router.replace(replacRouteStr))
        userInfo && (userInfo.homePath = replacRouteStr)
        this.setUserInfo(userInfo)
      }
      Watermark.set(`${userInfo?.kmYear || ''}  ${userInfo?.account || ''}`)
      return userInfo
    },
    setBASE_HOME(obj) {
      let astr = ''
      if (obj.hiddenChildren) {
        return obj.path
      }
      astr = obj.path + '/' + this.setBASE_HOME(obj.children[0])
      return astr
    },
    async getUserInfoAction(): Promise<UserInfo | null> {
      if (!this.getToken) return null
      const userInfo = await this.getUserInfo

      const { roles = [] } = userInfo
      if (isArray(roles)) {
        const roleList = roles.map(item => item.value) as RoleEnum[]
        this.setRoleList(roleList)
      } else {
        userInfo.roles = []
        this.setRoleList([])
      }
      return userInfo
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await doLogout()
        } catch {
          console.log('注销Token失败')
        }
      }

      Watermark.set('')
      this.userBehavior && this.userBehavior?.onStopDeactivated()//停止行为监听
      // this.userMySse && this.userInfo?.account && this.userMySse.disconnect(this.userInfo?.account, this.userInfo?.device)//停止sse监听
      this.setUserMySse(null)
      this.setToken(undefined)
      this.setAuthorityItem(null)
      this.setAuthority(null)
      this.setInfo(null)
      this.setSessionTimeout(false)
      this.setUserInfo(null)
      setAuthCache(EXAM_USER_INFO_KEY, null)
      goLogin && router.push(PageEnum.BASE_LOGIN)
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage()
      const { t } = useI18n()
      createConfirm({
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('sys.app.logoutMessage')),
        onOk: async () => {
          await this.logout(true)
        },
      })
    },
  },
})










// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore()
}
